import json
import os.path

from  apilib.component import compManager , TComp

class TCompIo ( TComp):
    def __init__(self):
        super().__init__()
        self.handlers={
            "read": self.read,
            "readObj": self.readObj,
            "write": self.write,
            "writeObj": self.writeObj
        }
        self.autoStartServices={}
    def getAbsFn(self , fn , autoCreatePath= False):
        res = ""
        try:
            rootPah = self.compSettings['rootPath'] if 'rootPath' in self.compSettings.keys() else ""
            if rootPah!="":
                res= rootPah+"/"+ fn
            else:
                res = fn
            dirName = os.path.dirname(res)
            if autoCreatePath and not  os.path.exists(dirName):
                os.makedirs(dirName , 0x777)
        except Exception as eer:
            self.manager.log(eer , self)
        return  res
    def read(self , fileName , default=''):
        res = default
        try:
            fn = self.getAbsFn(fileName)
            with open(fn, 'r' , encoding='utf-8') as  f:
                res = f.read()
        except Exception as eer:
            self.manager.log(eer , self)
        return  res
    def readObj(self , fileName , default={}):
        res = default
        try:
            content = self.read(fileName, "")
            if content!="":
                res = json.loads(content)
        except Exception as eer:
            self.manager.log(eer , self)
        return  res
    def write(self , fileName , content):
        res = False
        try:
            fn = self.getAbsFn(fileName)
            with open(fn, 'w' , encoding='utf-8') as  f:
                f.write(content)
            res = os.path.exists(fn)
        except Exception as eer:
            self.manager.log(eer , self)
        return  res
    def writeObj(self , fileName , obj):
        res = False
        try:
            content = json.dumps(obj , ensure_ascii=False)
            res = self.write(fileName , content)
        except Exception as eer:
            self.manager.log(eer , self)
        return  res

_settings={
    "rootPath":"/"
}
compManager.registComponentType('TCompIo' , TCompIo , _settings)